package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class JwtUtil {
    //创建一个Token(携带登录用户的信息)
    //登录用户的信息：1.用户名(账号)username  2.用户的Id  作为Token的payload（负载）




//因为这个是个工具类，为了方便调用所以写成静态方法(创建Token)
private static SecretKey secretKey = Keys.hmacShaKeyFor("6d6cd63284be4a47ba7aec4a3458939a95dcbdd5cd0438f23d7457099b4b917c4".getBytes());
    private  static long expireTime=60*60*1000;
    public static String createTonken(Long userId,String userName){

        String token = Jwts.builder()
                .setSubject("sysUser-token")
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(secretKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();

        return token;
    }





    //验证Token(解析Token)

    public static Claims parseToken(String token){
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);

            //获取负载数据
            Claims body = claimsJws.getBody();

            return body;
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
            //throw new RuntimeException(e);
        } catch (UnsupportedJwtException e) {
            throw new RuntimeException(e);
        }
    }







public static void main(String[] args) {
        String token = createTonken(1l,"zhangsan");
        System.out.println(token);


        Claims claims = parseToken(token);
    System.out.println(claims.get("userId"));
    System.out.println(claims.get("userName"));
}












}
